<?php

namespace App\Models;

use App\Constant;
use App\Services\DfChannel\DfChannelFactory;
use Illuminate\Database\Eloquent\Model;

class Payment extends Model
{
    //
    protected $guarded = ['id'];

    public $msg = '';

    public function withdraw()
    {
        return $this->belongsTo(SellerWithdrawRequest::class, 'withdraw_request_id', 'id');
    }

    public function push()
    {
        $channel_model = ManualDfMethod::find($this->channel_id);
        $client = DfChannelFactory::getChannel($channel_model->code);
        if(empty($client)) {
            return false;
        }
        $withdraw_model = $this->withdraw;

        $result = $client->pull($withdraw_model->id, $this->id, $this->channel_id);
        $this->_process($withdraw_model, $channel_model, $result['status']);
        if($result['status'] == Constant::NO) {
            if(!empty($result['msg'])) {
                $this->msg = $result['msg'] ?: 'Error';
                return false;
            }
        }

        return true;
    }

    public function _process($withdraw, $channel, $status)
    {
        if($status == 1) {
            $data['status'] = 1;
        }else {
            $data['status'] = 0;
        }

        $withdraw->fill($data)->save();
    }
}
